<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('cart_items', function (Blueprint $table) {
            $table->id();
            
            // 关联字段
            $table->foreignId('cart_id')->constrained()->onDelete('cascade')->comment('购物车ID');
            $table->foreignId('product_id')->constrained()->onDelete('cascade')->comment('产品ID');
            $table->foreignId('variant_id')->nullable()->constrained('product_variants')->onDelete('cascade')->comment('变体ID，可为空');
            
            // 商品信息
            $table->integer('quantity')->unsigned()->default(1)->comment('数量');
            $table->decimal('price', 10, 2)->comment('价格快照');
            $table->json('specifications')->nullable()->comment('规格信息快照');
            $table->string('image')->nullable()->comment('图片快照');
            $table->boolean('is_selected')->default(true)->comment('是否选中（用于结算）');
            
            // 价格审计字段
            $table->decimal('price_at_add', 10, 2)->nullable()->comment('加入购物车时的商品价格');
            $table->decimal('current_price', 10, 2)->nullable()->comment('当前商品价格');
            $table->timestamp('price_updated_at')->nullable()->comment('价格更新时间');
            
            $table->timestamps();
            
            // 唯一约束：同一购物车中同一产品的同一变体只能有一条记录
            $table->unique(['cart_id', 'product_id', 'variant_id']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('cart_items');
    }
};
